// pages/user/information/information.js
var httpUtil = require('../../../utils/httpUtil.js')
var uiUtil = require('../../../utils/uiUtil.js')
const app = getApp()
const mobile = /^1\d{10}$/;
var that

Page({

  /**
   * 页面的初始数据
   */
  data: {
    sex:["男","女"]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
    var userInfo = wx.getStorageSync('userInfo');
    that.setData({
      userName:userInfo.userName,
      index:userInfo.index,
      phone:userInfo.phone,
      date:userInfo.birth,
    })
  },

  /**
   * 选择性别和生日
   */
  bindSexChange: function (e) {
    this.setData({
      index: e.detail.value
    })
  },
  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  },

  /**
   * 信息校验
   */
  formSubmit:function(e){
    let value = e.detail.value;
    if (value.userName==""){
      uiUtil.showToast("请输入你的姓名");
    } else if (!mobile.test(value.phone)) {
      uiUtil.showToast("请输入正确的手机号");
    } else if (value.sex == ""){
      uiUtil.showToast("请选择你的性别");
    } else if (value.birth == ""){
      uiUtil.showToast("请选择你的生日");
    } else{
      uiUtil.showLoading("请稍候..");
      that.userBinding(value);
    }
  },


  /**
   * 提交用户信息
   */
  userBinding:function(e){
    let sex = parseInt(that.data.index)+1;
    
    httpUtil.PostRequest("handle_info", {
      userName: e.userName,
      phone: e.phone,
      sex: sex,
      birth: e.birth
    }, {
      success(res) {
        uiUtil.showToast("提交成功");

        e.index=that.data.index;
        wx.setStorageSync('userInfo', e);

        setTimeout(function(){
          var pages = getCurrentPages();
          var lastPage = pages[pages.length - 2];
          if (lastPage) {
            if (lastPage.route == "pages/index/navigationbar/navigationbar"){
              lastPage.onResultRegisterSuccess();
              wx.navigateBack({
                delta: 2,
              });
            } else{
              wx.redirectTo({
                url: "pages/index/navigationbar/navigationbar"
              })
            }
          } else {
            wx.redirectTo({
              url: "pages/index/navigationbar/navigationbar"
            })
          }
        },500);
      },
      fail(code, res) {
        uiUtil.showToast(res);
      },
      complete() { }
    })
  }
})